import { computed, nextTick, ref, type CSSProperties, type Ref } from "vue";
import { DomUtils } from "../utils/DomUtils";
import { Draggable } from "./Draggable";
import { diagonalSize, resizeHandles } from "./handle";
import type { HandleType, IDraggable, IRect, Vertex2D } from "./types";

const setPositionInfo = (
  dragRef: Ref<HTMLElement | null>,
  positionInfo: Ref<IRect>,
  zoom: number
) => {
  nextTick(() => {
    if (dragRef.value) {
      const dragRect = DomUtils.getDomBoundary(dragRef.value, zoom)!;
      const parentDom = DomUtils.getDomBoundary(dragRef.value.parentElement, zoom);
      const offset = {
        x: 0,
        y: 0
      };
      const halfWidth = dragRect.width / 2;

      const totalHeight = dragRect.height + 15;

      if (parentDom) {
        offset.x = parentDom.left;
        offset.y = parentDom.top;
      }

      positionInfo.value = {
        x: dragRect.left - offset.x + halfWidth,
        y: dragRect.top - offset.y + totalHeight,
        w: dragRect.width,
        h: dragRect.height,
        rotate: 0
      };
    }
  });
};

export const useDragData = () => {
  const handles = computed(() => {
    const { resizable } = rect.value;
    if (!resizable) {
      return resizeHandles;
    }
    return resizeHandles.concat(diagonalSize);
  });
  const positionInfo = ref<IRect>({
    w: 0,
    h: 0,
    x: 0,
    y: 0,
    rotate: 0
  });
  const snapPoint = Array.from({ length: 8 }, (_, i) => i * 45);

  const rect = ref<IDraggable>(new Draggable());
  const temporaryData = ref<{
    /* 识别：旋转|调整|拖拽 */
    behavior: HandleType;
    /* 鼠标方向 */
    mouseDirection: undefined;
  }>({
    /* 识别：旋转|调整|拖拽 */
    behavior: "drag",
    /* 鼠标方向 */
    mouseDirection: undefined
  });
  /* 顶点坐标 */
  const startCorners = ref<Vertex2D[]>(Array(4).fill({ x: 0, y: 0 }));
  const mouseRecord = {
    sx: 0, // 鼠标按下时的 x 坐标
    sy: 0, // 鼠标按下时的 y 坐标
    sw: 0,
    sh: 0,
    startAngle: -1, // 鼠标按下时的角度
    /* 顶点偏移量：X,Y */
    vx: 0,
    vy: 0,
    /* 真实偏移值,用于移动div */
    rx: 0,
    ry: 0
  };
  return {
    rect,
    mouseRecord,
    handles,
    temporaryData,
    startCorners,
    snapPoint,
    positionInfo,
    setPositionInfo
  };
};

export const useStyle = (rect: Ref<IDraggable>) => {
  /* 拖拽的状态,类名 */
  const handleStatusStyle = computed(() => {
    const { draggable, resizable, rotatable, disabled, className } = rect.value;
    return [
      {
        "no-drag": !draggable || disabled,
        "no-resize": !resizable,
        "no-rotate": !rotatable,
        disabled
      },
      className
    ];
  });

  const contentStyle = computed((): CSSProperties => {
    return {
      overflow: !rect.value.overflow ? "visible" : "hidden"
    };
  });
  return {
    contentStyle,
    handleStatusStyle
  };
};
